package com.myshop.controller;
import com.myshop.entity.R;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

/**
 * 文件上传下载
 */
@RestController
@RequestMapping("/file")
@CrossOrigin(origins = "*")
public class FileController {

    @Value("${file.uploader}")
    private String uploadPath;

    /**
     * 文件上传
     * @return
     */
    @RequestMapping("/uploader")
    public R upload(MultipartFile file){

        File filePath = new File(uploadPath);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }

        //准备文件名称
        String fileName = UUID.randomUUID().toString();
        try (
                InputStream in = file.getInputStream();
                OutputStream out = new FileOutputStream(new File(filePath, fileName));
        ){
            IOUtils.copy(in, out);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return R.succ(fileName);
    }

    /**
     * 文件的下载
     * @param fileName
     * @param response
     */
    @RequestMapping("/download")
    public R download(String fileName, HttpServletResponse response) {
        File file = new File(uploadPath, fileName);
        if (!file.exists())
            return R.fail(40004, "下载出现异常");
        try (
                InputStream in = new FileInputStream(file);
                OutputStream out = response.getOutputStream();
        ) {
            IOUtils.copy(in, out);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return R.succ("上传的响应");
    }
}
